<template>
  <!-- // 分配角色 -->
  <div>
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getRoles } from '@/api/roles'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employess'
export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleIds: [], // 选中的角色列表
      roles: []
    }
  },
  created() {
    this.loadRoles()
    this.loadRoleIds()
  },
  methods: {
    closeDialog() {
      this.$emit('close')
    },
    async loadRoles() {
      // 获取所有的角色列表
      try {
        const res = await getRoles()
        this.roles = res.data.rows
      } catch (e) {
        console.log(e)
      }
    },
    // 根据父组件传递过来的 id 获取用户对应的角色id
    async loadRoleIds() {
      try {
        const res = await getUserDetailById(this.id)
        // console.log(res)
        this.roleIds = res.data.roleIds
      } catch (e) {
        console.log(e)
      }
    },
    resetIds() {
      this.roleIds = []
    },
    async hSubmit() {
      try {
        const res = await assignRoles({ id: this.id, roleIds: this.roleIds })
        this.$message.success(res.message)
        this.$emit('close')
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  }
}
</script>
